package bigbrother.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

public class ConnectionHandler {
	
	private ConnectionHandler(){}
	Logger logger = LogManager.getLogger(ConnectionHandler.class);
	private static ConnectionHandler handler;
	public static ConnectionHandler getHandler(){
		if(handler==null){
			handler = new ConnectionHandler();
		}
		return handler;
	}
	
	
	public Connection getConnection() {
		Connection conn =null;
		try {
			Context initContext = new InitialContext();
			Context envContext  = 
					(Context)initContext.lookup("java:/comp/env");
			BasicDataSource ds = 
					(BasicDataSource)envContext.lookup("jdbc/myoracle");
			conn = ds.getConnection();
		} catch (NamingException |SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public Connection getConnection_old() throws SQLException {
		try {
			Class.forName("oracle.jdbc.OracleDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "jdbc:oracle:thin:@localhost:1521:orcl";
		String user = "scott";
		String pass = "tiger";
		return DriverManager.getConnection(url, user, pass);
	}
	public void rollback(Connection con){
		try {
			con.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void setCommit(Connection con, boolean commit){
		try {
			con.setAutoCommit(commit);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void close(Connection con) {
		try {
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
